package org.graduation.IM.hanlder;

import com.corundumstudio.socketio.SocketIOClient;
import com.corundumstudio.socketio.SocketIOServer;
import com.corundumstudio.socketio.annotation.OnConnect;
import com.corundumstudio.socketio.annotation.OnDisconnect;
import lombok.extern.slf4j.Slf4j;
import org.graduation.IM.service.socket.SocketService;
import org.graduation.utils.Token;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;


@Slf4j
@Component
public class SocketIOHandler {
    @Autowired
    private SocketIOServer socketIoServer;//服务端对象
    @Autowired
    private SocketService socketService;
    @Autowired
    private Token tokenTool;

    //Spring IoC容器创建之后，在加载SocketIOService Bean之后启动
    //服务端启动
    @PostConstruct
    private void autoStartup() throws Exception {
        try {
            socketIoServer.start();
        } catch (Exception ex) {
            ex.printStackTrace();
            log.error("SocketIOServer启动失败");
        }
    }

    //Spring IoC容器在销毁SocketIOService Bean之前关闭,避免重启项目服务端口占用问题
    //服务端关闭
    @PreDestroy
    private void autoStop() throws Exception {
        socketIoServer.stop();
    }

    //客户端连接的时候触发
    @OnConnect
    public void onConnect(SocketIOClient client) {
        String token = getToken(client); // 或者从客户端发送的事件中获取
        if (token != null) {
            socketService.login(tokenTool.getUidByToken(token), client);
        } else {
            log.warn("Failed to obtain user token from the connecting client.");
            // 可能需要考虑拒绝连接或发送错误消息给客户端
        }
    }

    //客户端关闭连接时触发
    @OnDisconnect
    public void onDisconnect(SocketIOClient client) {
        String token = getToken(client);
        if (token != null) {
            socketService.logout(tokenTool.getUidByToken(token));
        }
    }

    private String getToken(SocketIOClient client){
        return client.getHandshakeData().getSingleUrlParam("token");
    }
}